package com.woniu.darryringmall.ucenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.darryringmall.front.entity.*;
import com.woniu.darryringmall.front.service.*;
import com.woniu.darryringmall.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController("ucenterController")
@RequestMapping("ucenter/user")
public class UserController {
    @Autowired
    private DistrictService districtService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private HistoryService historyService;

    /**
     * 获取用户头像
     * @return
     */
    @PostMapping("userAvator")
    public ResponseData userAvator(HttpSession session){
        User user=(User)session.getAttribute("user");
        String avator=user.getAvator();
        return new ResponseData(avator);
    }

    /**
     * 获取热销商品
     */
    @PostMapping("hotGoods")
    public ResponseData hotGoods(){
        //获取热销商品
        List<HotGoods> hotgoods=goodsService.hotlist();
        return new ResponseData(hotgoods);
    }

    /**
     * 获取用户浏览过的商品(只能查询最近浏览的5个商品)
     */
    @PostMapping("goodsHistory")
    public ResponseData goodsHistory(HttpSession session){
        User user=(User) session.getAttribute("user");
        List<HistoryGoods> historyGoods=historyService.getHistoryByUserId(user.getId());
        return new ResponseData(historyGoods);
    }

    /**
     * 进入个人信息页面
     * @return
     */
    @PostMapping("info")
    public ResponseData updateInfo(){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("pid",0);
        List<District> province = districtService.list(wrapper);
        return new ResponseData(province);
    }

    /**
     * 修改个人信息
     * @param address
     * @return
     */
    @PostMapping("updateinfo")
    public ResponseData updateInfo (Address address,HttpSession session){
        User user=(User)session.getAttribute("user");
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        userService.updateById(user);
        address.setUserId(user.getId());
        address.setAccept(user.getName());
        address.setIsDefault("y");
        addressService.save(address);
        return ResponseUtils.SUCCESS;
    }

    /**
     * 修改头像
     * @param file
     * @param session
     * @return
     */
    @PostMapping("updateAvator")
    public ResponseData updateAvator(MultipartFile file,HttpSession session){
        String imgPath = TencentCOSUtil.uploadfile(file);
        User user = (User)session.getAttribute("user");
        user.setAvator(imgPath);
        userService.updateById(user);
        return new ResponseData(ResultStateCode.SUCCESS,"修改成功");
    }

    /**
     * 通过用户名称从redis获取用户系统消息数量
     * @param session
     * @return
     */
    @PostMapping("messageNum")
    public ResponseData getMessageNum(HttpSession session){
        User user = (User)session.getAttribute("user");
        String messageNum = redisTemplate.opsForValue().get(user.getName());
        int num = 0;
        if(messageNum==null || Integer.parseInt(messageNum)<=0){
            redisTemplate.delete(user.getName());
        }else{
            num = Integer.parseInt(messageNum);
        }
        return new ResponseData(num);
    }

    /**
     * 修改密码
     * @param code
     * @param newpwd
     * @param renewpwd
     * @return
     */
    @PostMapping("pwd")
    public ResponseData updatePasswordById( String code,String newpwd,String renewpwd,String phone,HttpSession session){
        System.out.println(code);
        System.out.println(newpwd);
        System.out.println(renewpwd);
        System.out.println(phone);

        if(code==null || newpwd==null || renewpwd==null || phone==null){
            return new ResponseData(ResultStateCode.FAIL,"请填写完整的信息");
        }
        String result = redisTemplate.opsForValue().get(phone);
        if(result==null){
            return new ResponseData(ResultStateCode.FAIL,"验证码已过期");
        }else if(!code.equals(result)){
            return new ResponseData(ResultStateCode.FAIL,"验证码不正确");
        }
        if(!newpwd.equals(renewpwd)){
            return new ResponseData(ResultStateCode.FAIL,"两次密码不一致");
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        //TODO 从session获取用户id
        wrapper.eq("telephone",phone);
        wrapper.set("password",newpwd);
        userService.update(wrapper);
        return new ResponseData(ResultStateCode.SUCCESS,"密码修改成功");
    }

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @PostMapping("code")
    public ResponseData sendCode( String phone){
        log.debug("电话号码：{}",phone);
        ValueOperations<String, String> redis = redisTemplate.opsForValue();
        //TODO 从session获取用户名判断验证码是否存在
        String result = redis.get(phone);
        log.debug("验证码：{}",result);
        if(result!=null){
            return new ResponseData(ResultStateCode.FAIL,"验证码未过期，请及时填写");
        }
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        String[] phones = {TencentSmsUtil.prefix+phone};
        String[] codes = {code,"1"};
        try{
            TencentSmsUtil.sendSms(phones,codes);
            redis.set(phone,code,1, TimeUnit.MINUTES);
            System.out.println(redis.get(phone));
            return new ResponseData(ResultStateCode.SUCCESS,"验证码发送成功，请及时填写");
        }catch (RuntimeException e){
            e.printStackTrace();
            return new ResponseData(ResultStateCode.FAIL,"验证码发送失败，请重新申请");
        }
    }


    @PostMapping("address")
    public ResponseData address(HttpSession session){
        List<Address> addresses = addressService.list(new QueryWrapper<Address>().eq("userid", ((User)session.getAttribute("user")).getId()));
        return new ResponseData(addresses);
    }




    @PostMapping("getmessage")
    public ResponseData getMessage(HttpSession session){
        //TODO 从session获取用户id
        User user=(User)session.getAttribute("user");
        List<Message> messages = messageService.list(new QueryWrapper<Message>().eq("userid", user.getId()));
        ResponseData responseData = new ResponseData<>();
        responseData.setCode(0);
        responseData.setData(messages);
        return responseData;
    }



    @PostMapping("delstatusbyid")
    public ResponseData delStatusById(int[] ids){
        System.out.println(ids.length);
        List list = new ArrayList();
        for (int i = 0; i < ids.length; i++) {
            list.add(ids[i]);
        }
        boolean flag = messageService.removeByIds(list);
        if (!flag){
            return new ResponseData(ResultStateCode.FAIL,"删除失败！");
        }
        return new ResponseData(ResultStateCode.SUCCESS,"删除成功！");
    }


    @PostMapping("updatestatusbyid")
    public ResponseData updateStatusById(int[] ids){
        List list = new ArrayList();
        for (int i = 0; i < ids.length; i++) {
            list.add(ids[i]);
        }
        boolean flag = messageService.update(new UpdateWrapper<Message>().in("id",list).set("status","已读"));
        if (!flag){
            return new ResponseData(ResultStateCode.FAIL,"修改失败！");
        }
        return new ResponseData(ResultStateCode.SUCCESS,"修改成功！");
    }

}
